package com.c.opt.query;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.c.opt.enums.EnumQueryLinkRule;
import com.c.opt.enums.EnumQueryRuleType;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import ntd.util.frame.data.bo.QueryRuleInfo;

import java.util.List;
import java.util.Map;
import java.util.Set;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ComQueryInfo {

    /** 链接规则 */
    private EnumQueryLinkRule enumQueryLinkRule = EnumQueryLinkRule.RULE_AND;

    /** 字段名称 */
    private String name;

    /** 字段值 */
    private String val;

    /** 字段值组 */
    private List<String> values;

    /** 查询类型 */
    private EnumQueryRuleType queryRuleType = EnumQueryRuleType.RULE_EQ;

    public ComQueryInfo(String name, String val, EnumQueryRuleType queryRuleType) {
        this.name = name;
        this.val = val;
        this.queryRuleType = queryRuleType;
    }

    public ComQueryInfo(EnumQueryLinkRule enumQueryLinkRule, String name, String val, EnumQueryRuleType queryRuleType) {
        this.enumQueryLinkRule = enumQueryLinkRule;
        this.name = name;
        this.val = val;
        this.queryRuleType = queryRuleType;
    }

    public ComQueryInfo(String name, List<String> values, EnumQueryRuleType queryRuleType) {
        this.name = name;
        this.values = values;
        this.queryRuleType = queryRuleType;
    }

    public ComQueryInfo(String key, EnumQueryRuleType ruleIsNull) {
        this.name = key;
        this.queryRuleType = ruleIsNull;
    }

    public static List<ComQueryInfo> transform(String rules) {
        if(StrUtil.isBlank(rules)){
            return ListUtil.empty();
        }
        final Set<Map.Entry<String, Object>> ruleSet = JSONUtil.parseObj(rules).entrySet();
        return CollStreamUtil.toList(ruleSet, rule -> {
            ComQueryInfo queryRuleInfo = new ComQueryInfo();
            final String[] keys = rule.getKey().split("__");
            queryRuleInfo.setName(keys[0]);
            queryRuleInfo.setVal(Convert.toStr(rule.getValue()));
            queryRuleInfo.setQueryRuleType(EnumQueryRuleType.val(keys[1]));
            return queryRuleInfo;
        });
    }
}
